package me.send.business.service.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.send.business.base.ErrorEntity;
import me.send.business.base.Page;
import me.send.business.base.SendVariable;
import me.send.business.base.jpush.JPush;
import me.send.business.service.BaseService;
import me.send.business.service.bean.CompletedBean;
import me.send.business.service.bean.OrderBrokerBean;
import me.send.business.service.bean.OrderInfoBean;
import me.send.business.service.cons.OrderCons;
import me.send.business.service.cons.ProgressCons;
import me.send.business.service.cons.PushStr;
import me.send.business.service.mapper.AdvertMapper;
import me.send.business.service.mapper.FundMapper;
import me.send.business.service.mapper.OpencityMapper;
import me.send.business.service.mapper.OrderProgressMapper;
import me.send.business.service.mapper.OrderpicMapper;
import me.send.business.service.mapper.OrdersMapper;
import me.send.business.service.pojo.Advert;
import me.send.business.service.pojo.OrderInfoV1_1_1Bean;
import me.send.business.service.pojo.OrderProgress;
import me.send.business.service.pojo.Orderpic;
import me.send.business.service.pojo.Orders;
import me.send.framework.util.HelperUtil;
import me.send.framework.util.LoggerUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.jpush.api.JPushClient;

@Service
public class OrdersService extends BaseService {

	@Autowired
	private OrdersMapper ordersMapper;

	@Autowired
	private OrderpicMapper orderpicMapper;

	@Autowired
	private OpencityMapper opencityMapper;
	
	@Autowired
	private AdvertMapper advertMapper;
	
	@Autowired
	private FundMapper fundMapper;
	
	@Autowired
	private OrderProgressMapper orderProgressMapper;

	// 做一些验证 订单的方法
	public ErrorEntity verification(String devicenumber, int orderid) {
		ErrorEntity entity = error_1000();
		if (isDevicenumber(devicenumber)) {
			if (orderid != 0) {
				// 查询 这个userid 的 对象
				Map<String, Object> result = ordersMapper
						.one_map_orderid(orderid);
				// 获取这个结果下面的 创建时间
				String createtime = result.get("createtime").toString();
				// 判断这个 创建时间 是否是null 如果是null 返回一个错误码
				if (createtime == null || createtime.equals("")) {
					entity = error_1001();
				}
				try {
					// 获取订单的创建时间 2015年6月4日15:54:53
					long createtime_long = HelperUtil.simpleDateFormat.parse(
							createtime).getTime();
					long configuration_long = Long
							.parseLong(getConfigurationValue(
									SendVariable.user_order_time).toString()) * 60 * 1000;
					// 如果创建时间 + 配置文件里面的时间 大于当前的时间 说明这个订单已经失效
					if (createtime_long + configuration_long > System
							.currentTimeMillis()) {
						entity = error_1004();
					}
				} catch (Exception e) {
					e.printStackTrace();
					return entity;
				}

			} else {
				entity = error_1006();
			}
		} else {
			entity = error_1002();
		}
		return entity;
	}

	// 编辑 取消 订单 系统变量 user_order_time
	public ErrorEntity delete_orders_orderid(String devicenumber, int orderid) {
		// 验证String devicenumber的验证
		ErrorEntity entity = error_1000();
		if (isDevicenumber(devicenumber)) {
			// 判断这个orderID 是否是 0
			if (orderid != 0) {
				// 判断这个订单 2015年6月4日15:36:52
				ordersMapper.delete_orders_orderid(orderid); // 根据订单号查询结果
				entity = error_1000();
			} else {
				entity = error_1006();
			}
		} else {
			entity = error_1002();
		}
		return entity;
	}

	/**
	 * 用户取消订单
	 * 
	 * @param orderid
	 * @return
	 */
	public int deleteOrder(int orderid, int userid) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderid", orderid);
		params.put("userid", userid);
		// 需要加入条件判断
		// TODO
		return ordersMapper.deleteOrder(params);
	}
	
	/**
	 * 用户申请取消订单
	 * 
	 * @param orderid
	 * @return
	 */
	public int needCancelOrder(int orderid, int userid) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderid", orderid);
		params.put("userid", userid);
		//OrderInfoV1_1Bean order=getOrderInfoForV1_1(orderid);
		OrderInfoV1_1_1Bean order=getOrderInfoForV1_1_1(orderid);
		// 需要加入条件判断
		if(order.getNeedCancel()==1){
			return -1;
		}
		if(order.getStatus()==8||order.getStatus()==9||order.getStatus()==1||order.getStatus()==2){
			return -2;
		}
		// TODO
		return ordersMapper.needCancelOrder(params);
	}

	// 查看订单 2015年6月4日14:46:38
	public Map<String, Object> one_orderid(String devicenumber, int orderid) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 实例化一个接受的map 对象
		Map<String, Object> result = new HashMap<String, Object>();
		// 验证String devicenumber的验证
		ErrorEntity entity = error_1000();
		if (isDevicenumber(devicenumber)) {
			// 判断这个orderID 是否是 0
			if (orderid != 0) {
				result = ordersMapper.one_map_orderid(orderid); // 根据订单号查询结果
				entity = error_1000();
			} else {
				entity = error_1006();
			}
		} else {
			entity = error_1002();
		}
		map.put(SendVariable.COMM_ERROR, entity);
		map.put(SendVariable.COMMON_OBJECT, result);
		// 返回最后的map
		return map;
	}
	
	// 查看订单 2015年6月4日14:46:38
	public Map<String, Object> queryOrder(int orderid) {
		Map<String, Object> result = new HashMap<String, Object>();
		result = ordersMapper.one_map_orderid(orderid); // 根据订单号查询结果
		return result;
	}

	// 增加小费 2015年6月4日14:36:28 追加小费
	public int update_tip_orderid(int orderid, Double tip, String devicenumber) {
		Orders orders = new Orders();
		orders.setOrderid(orderid);
		orders.setTip(tip.doubleValue());
		// 判断 devicenumber 是否是null 如果是null
		orders.setUpdatetime(HelperUtil.getCurrentDate()); // 设置当前时间
		return ordersMapper.update_tip_orderid(orders);
	}

	/**
	 * 用户增加小费
	 * 
	 * @param tip
	 * @param orderid
	 * @return
	 */
	public int addTip(double tip, int orderid, int userid) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tip", tip);
		param.put("orderid", orderid);
		param.put("userid", userid);
		param.put("updatetime", HelperUtil.getCurrentDate());
		return ordersMapper.addTip(param);
	}

	// 个人呼送记录
	public Map<String, Object> list_page_userid(int userid, Page page,
			String devicenumber) {
		// 判断
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(SendVariable.COMM_ERROR, error_1001());
		map.put(SendVariable.COMMON_LIST, new ArrayList<Map<String, Object>>());
		if (isDevicenumber(devicenumber)) {
			if (page == null) {
				page = new Page();
			}

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("page", page);
			param.put("userid", userid);

			List<Map<String, Object>> list = ordersMapper
					.list_page_userid(param);
			map.put(SendVariable.COMMON_LIST, list);
			map.put(SendVariable.COMM_ERROR, error_1000());
		} else {
			map.put(SendVariable.COMM_ERROR, error_1002());
		}
		return map;
	}

	public List<CompletedBean> completedOrders(int userid, int startid, int size,
			String devicenumber) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userid", userid);
		params.put("startid", startid);
		params.put("size", size);
		return ordersMapper.completedOrders(params);
	}

	// 增加数据 2015年6月2日11:28:52
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ErrorEntity release_userid(Orders orders, String devicenumber,
			List<String> picpathList) {
		if (orders == null) {
			// 如果对象不存在 返回一个对象不存在
			return error_1006();
		} else {
			if (isDevicenumber(devicenumber)) {
				try {
					// 获取到用户的主键 2015年6月10日17:00:26
					//int orderid_max = ordersMapper.max_id();
					//orders.setOrderid(orderid_max);
					orders.setCreatetime(HelperUtil.getCurrentDate());
					orders.setStatus(1);
					int type = 0;
					if (orders.getDescption() != null
							&& !orders.getDescption().equals("")) {
						type = 1;
					}
					if (orders.getVoicepath() != null
							&& !orders.getVoicepath().equals("")) {
						type = 2;
					}
					String cityname = orders.getCityname();
					if (cityname != null && !"".equals(cityname)) {
						int cityId = opencityMapper.getCityIdByName(cityname);
						orders.setCityid(cityId);
					}
					// 调用mapper下面的保存方法 2015年6月2日11:31:10
					orders.setType(type);
					int advertId = orders.getAdvertId();
					LoggerUtils.info(getClass().getName(), "advertId："+advertId);
					
					Advert advert = advertMapper.getAdvertById(advertId);
					if (advertId>0) {
						double discount = advert.getOriginalPrice()-advert.getDiscountPrice();
						LoggerUtils.info(getClass().getName(), "discount："+discount);
						if (fundMapper.getAmountByFundCode()<discount) {
							LoggerUtils.info(getClass().getName(), "");
							//将活动广告置为不可用
							new Thread(new Runnable() {
								public void run() {
									advertMapper.updateAdvertStatusOfAll();
								}
							}).start();
							//活动资金池金额不足
							return new ErrorEntity("1008", "amount is not enough", "活动结束");
						}else {
							orders.setDiscount(discount);
							orders.setFee(advert.getDiscountPrice());
							orders.setAdvertId(advertId);
						}
					}
					ordersMapper.release_userid(orders);

					// 保存图片和语音 调用图片保存方法 2015年6月10日17:09:37
					for (String picpath : picpathList) {
						Orderpic orderpic = new Orderpic();
						orderpic.setCreatetime(HelperUtil.getCurrentDate());
						orderpic.setOrderid(orders.getOrderid());
						orderpic.setPicpath(picpath);
						orderpicMapper.save(orderpic);
					}
					final String lgt=orders.getLongitude();
					final String lat=orders.getLatitude();
					final int orderid=orders.getOrderid();
					new Thread(new Runnable() {
						public void run() {
							// 发送通知
							JPushClient brokerClient = JPush.getBrokerJPushClient();
							JPush.pushLBSMessageAll(brokerClient, PushStr.ORDER_CREATE, lgt, lat);
							//保存进度
							OrderProgress op= new OrderProgress();
							op.setUserMsg(ProgressCons.ORDER_CREATE_MSG);
							op.setContent(ProgressCons.ORDER_CREATE_CONTENT);
							op.setOrderid(orderid);
							op.setOrderStatus(OrderCons.ORDER_CREATEED);
							op.setCreatetime(HelperUtil.getCurrentDate());
							op.setUpdatetime(HelperUtil.getCurrentDate());
							orderProgressMapper.addOrderProgress(op);
						}
					}).start();
					// 成功的话 直接返回 成功的错误码
					return error_1000();
				} catch (Exception e) {
					e.printStackTrace();
					// 如果报错 返回 系统错误
					return error_1001();
				}
			} else {
				return error_1002();
			}
		}
	}

	public List<OrderBrokerBean> orderBrokerList(String devicenumber,
			Integer orderid,int type) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderid", orderid);
		params.put("type", type);
		return ordersMapper.order_broker_list(params);
	}

	/**
	 * 用户确认完成
	 * 
	 * @param params
	 * @return
	 */
	public int confirmComplet(int orderid) {
		return ordersMapper.updateStatus(orderid);
	}

	public String getBrokerIsvAccountByOrderId(int orderid) {
		return ordersMapper.getBrokerIsvAccountByOrderId(orderid);
	}

	public int getBrokerIdByOrderId(int orderid) {
		return ordersMapper.getBrokerIdByOrderId(orderid);
	}

	public OrderInfoBean getOrderInfo(int orderid) {
		return ordersMapper.getOrder(orderid);
	}
//	public OrderInfoV1_1Bean getOrderInfoForV1_1(int orderid) {
//		return ordersMapper.getOrderForV1_1(orderid);
//	}
	public OrderInfoV1_1_1Bean getOrderInfoForV1_1_1(int orderid) {
		return ordersMapper.getOrderForV1_1_1(orderid);
	}
	public int completEvaluate(int orderid){
		return ordersMapper.completEvaluate(orderid);
	}
	
	public List<OrderProgress> getOrderProgressesByOrderId(int orderid){
		return orderProgressMapper.getOrderProgressesByOrderId(orderid);
	}
	
	public Map<String, String> getOrderLocation(int orderid){
		return ordersMapper.getOrderLocation(orderid);
	}
}
